package com.xy.xymall.ware.service.impl;

import com.xy.common.exception.NoStockException;
import com.xy.common.utils.R;
import com.xy.xymall.ware.feign.ProductFeignService;
import com.xy.xymall.ware.vo.OrderItemVo;
import com.xy.xymall.ware.vo.SkuHasStockVo;
import com.xy.xymall.ware.vo.WareSkuLockVo;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xy.common.utils.PageUtils;
import com.xy.common.utils.Query;

import com.xy.xymall.ware.dao.WareSkuDao;
import com.xy.xymall.ware.entity.WareSkuEntity;
import com.xy.xymall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;
    /**
     *分页查询仓库库存信息
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId=(String)params.get("skuId");
        if(!StringUtils.isEmpty(skuId)){
            queryWrapper.eq("sku_id",skuId);
        }
        String wareId=(String)params.get("wareId");
        if(!StringUtils.isEmpty(wareId)){
            queryWrapper.eq("ware_id",wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //如果没有库存记录则进行插入而不是更新
        Integer integer = wareSkuDao.selectCount(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if(integer==null||integer==0){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字
            //这里使用try-catch  如果设置sku名字出异常了还是继续执行，并不需要事务回滚
            //TODO 还可以用什么办法让异常出现以后不需要回滚？
            try{
                R info = productFeignService.info(skuId);
                Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");
                if(info.getCode()==0){
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            }catch (Exception e){

            }
            this.save(wareSkuEntity);
        }else{
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }

    }

    //查询是否有库存
    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        return skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            //库存量减去被锁定库存量
            Long count=baseMapper.getSkuStock(skuId);
            vo.setSkuId(skuId);
            vo.setHasStock(count != null && count > 0);
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * @param lockVo
     * @author XY
     * @date 2021/1/19 11:13
     * @Description 为某个订单锁定库存
     */
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo lockVo) {
        //1、按照下单的收货地址找到一个最近的仓库，锁定库存。
        //1、找到每个商品在哪个仓库都有库存。
        List<OrderItemVo> locks = lockVo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            //查询这个商品在哪里有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());
        //2、锁定
        for (SkuWareHasStock stock : collect) {
            boolean skuStocked=false;
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareId();
            if(wareIds==null || wareIds.size()==0){
                throw new NoStockException(skuId);
            }
            for (Long wareId : wareIds) {
                //成功返回1
                Long count =wareSkuDao.lockSkuStock(skuId,wareId,stock.getNum());
                if (count == 1) {
                    skuStocked=true;
                    break;
                }
            }
            if(!skuStocked){
                //当前商品没锁住
                throw new NoStockException(skuId);
            }
        }
        //3、全部锁定成功
        return true;
    }

    @Data
    private class SkuWareHasStock{
      private Long skuId;
      private Integer num;
      private List<Long> wareId;
    }

}